package com.xlyy.modbus.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.xlyy.modbus.entity.Categorize;
import com.xlyy.modbus.entity.MyTestresult;
import com.xlyy.modbus.service.IMyDataService;
import com.xlyy.modbus.service.IMyTestresultService;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class WebsocketController {
    private static ConcurrentHashMap<String, WebsocketController> webSocketMap = new ConcurrentHashMap<>();

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    //实例一个session，这个session是websocket的session
    private Session session;

    //新增一个方法用于主动向客户端发送消息
    public static void sendMessage(Object message, String userId) {
        WebsocketController webSocket = webSocketMap.get(userId);
        if (webSocket != null) {
            try {
                webSocket.session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));
//                System.out.println("【websocket消息】发送消息成功,用户="+userId+",消息内容"+message.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static ConcurrentHashMap<String, WebsocketController> getWebSocketMap() {
        return webSocketMap;
    }

    public static void setWebSocketMap(ConcurrentHashMap<String, WebsocketController> webSocketMap) {
        WebsocketController.webSocketMap = webSocketMap;
    }

    //前端请求时一个websocket时
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
//        this.session.getUserProperties().put("org.apache.tomcat.websocket.BLOCKING_SEND_TIMEOUT",-1);
        webSocketMap.put(userId, this);
//        System.out.println("【websocket消息】有新的连接,连接id"+userId);
    }

    //前端关闭时一个websocket时
    @OnClose
    public void onClose(@PathParam("userId") String userId) {
        webSocketMap.remove(userId);
//        System.out.println("【websocket消息】连接断开,总数:"+ webSocketMap.size());
    }

    //前端向后端发送消息
    @OnMessage
    public void onMessage(String message) {
//        if (!message.equals("ping")) {
//            System.out.println("【websocket消息】收到客户端发来的消息:"+message);
//        }
    }

//    @Override
//    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
//        IMyTestresultService myTestresultService = applicationContext.getBean(IMyTestresultService.class);
//        scheduler.scheduleAtFixedRate(() -> {
//            try {
//                MyTestresult myTestresult = myTestresultService.lastMyTestresult();
//                if(myTestresult!=null && webSocketMap.size()>0){
//                    sendMessage(myTestresult,"modbusSystem");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }, 0, 1, TimeUnit.SECONDS);
//
//    }

}
